package com.example.neartweet;

import com.example.neartweet.TwitterApp.TwDialogListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class SettingsActivity extends Activity {

	private EditText userText;
	private Button login;
	private boolean location;
	private CheckBox twitterConn;
	private TwitterApp mTwitter;

	private static final String twitter_consumer_key = "9bO9i0f0urTGfSx4LqNJA";
	private static final String twitter_secret_key = "nnBmT2sLwnsMbPMTdoWuOzRJRCJHPIfYdiIrub0DKQ";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_settings);
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setTitle("Settings");
		userText = (EditText) findViewById(R.id.set_useredit);
		login = (Button) findViewById(R.id.set_login);
		
		SharedPreferences sharedPrefs = getSharedPreferences(
		        getString(R.string.preference_file_key),MODE_PRIVATE);
		int state = sharedPrefs.getInt("gps", 0);
		if (state == 0){
			location = false;
		} else {
			location = true;
		}


		twitterConn = (CheckBox) findViewById(R.id.twitterCheck);

		twitterConn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onTwitterClick();
			}
		});

		mTwitter    = new TwitterApp(this, twitter_consumer_key,twitter_secret_key);

		mTwitter.setListener(mTwLoginDialogListener);

		if (mTwitter.hasAccessToken()) {
			twitterConn.setChecked(true);

			String username = mTwitter.getUsername();
			username = (username.equals("")) ? "Unknown" : username;

			twitterConn.setText("  Twitter (" + username + ")");
			twitterConn.setTextColor(Color.BLACK);
		}

		userText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {

				Boolean canLogin = userText.getText().toString().length() > 0;
				login.setEnabled(canLogin);

			}
		});

		login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				saveUser(userText.getText().toString());
				SharedPreferences sharedPrefs = getSharedPreferences(
						getString(R.string.preference_file_key),MODE_PRIVATE);
				SharedPreferences.Editor editor = sharedPrefs.edit();
				editor.putInt("state", 0);
				editor.commit();
				finish();				
			}
		});

		loadPrefs();

	}

	private void onTwitterClick() {
		if (mTwitter.hasAccessToken()) {
			final AlertDialog.Builder builder = new AlertDialog.Builder(this);

			builder.setMessage("Delete current Twitter connection?")
			.setCancelable(false)
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					mTwitter.resetAccessToken();

					twitterConn.setChecked(false);
					twitterConn.setText("  Twitter (Not connected)");
					twitterConn.setTextColor(Color.BLACK);
				}
			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.cancel();

					twitterConn.setChecked(true);
				}
			});
			final AlertDialog alert = builder.create();

			alert.show();
		} else {
			twitterConn.setChecked(false);

			mTwitter.authorize();
		}
	}

	private final TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
		@Override
		public void onComplete(String value) {
			String username = mTwitter.getUsername();
			username        = (username.equals("")) ? "No Name" : username;

			twitterConn.setText("  Twitter  (" + username + ")");
			twitterConn.setChecked(true);
			twitterConn.setTextColor(Color.BLACK);

			Toast.makeText(SettingsActivity.this, "Connected to Twitter as " + username, Toast.LENGTH_LONG).show();
		}

		@Override
		public void onError(String value) {
			twitterConn.setChecked(false);

			Toast.makeText(SettingsActivity.this, "Twitter connection failed", Toast.LENGTH_LONG).show();
		}
	};



	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.settings, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;
		SharedPreferences sharedPrefs = getSharedPreferences(
		        getString(R.string.preference_file_key),MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPrefs.edit();
		switch (item.getItemId()) {
		case android.R.id.home:
			SettingsActivity.this.finish();
			break;
		case R.id.gps:
			if(location) {
				item.setIcon(R.drawable.gps_off);
				location = false;
				
				editor.putInt("gps", 0);
				editor.commit();
			} else {
				item.setIcon(R.drawable.gps_on);
				location = true;
				
				editor.putInt("gps", 1);
				editor.commit();
			}
			break;
		case R.id.poll:
			intent = new Intent(this, PollActivity.class);
			startActivity(intent);
			SettingsActivity.this.finish();
			break;
		case R.id.compose:
			intent = new Intent(this, ComposeActivity.class);
			startActivity(intent);
			SettingsActivity.this.finish();
			break;
		default:

		}
		return super.onOptionsItemSelected(item);
	}

	private void loadPrefs() {

		SharedPreferences sharedPrefs = getSharedPreferences(
				getString(R.string.preference_file_key),MODE_PRIVATE);
		String uN = sharedPrefs.getString("usr", "");
		userText.setText(uN);

	}

	private void saveUser(String str) {

		SharedPreferences sharedPrefs = getSharedPreferences(
				getString(R.string.preference_file_key),MODE_PRIVATE);
		SharedPreferences.Editor editor = sharedPrefs.edit();
		editor.putString("usr", str);
		editor.commit();

	}

}
